package com.sdkj.fixed.asset.hc.util;


import com.google.common.collect.Lists;
import com.sdkj.fixed.asset.hc.pojo.ProductTypeTree;
import lombok.experimental.UtilityClass;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wyh
 * @date 2019年11月9日23:34:11
 */
@UtilityClass
public class TreeUtil {
    /**
     * 两层循环实现建树
     *
     * @param treeNodes 传入的树节点列表
     * @return
     */
    public <T extends TreeNode> List<T> bulid(List<T> treeNodes, Object root) {
        List<T> trees = new ArrayList<>();

        for (T treeNode : treeNodes) {
            if (root.equals(treeNode.getParentId())) {
                trees.add(treeNode);
            }
            List<TreeNode> children = Lists.newArrayList();
            for (T it : treeNodes) {
                if (it.getParentId().equals(treeNode.getId())) {
                    children.add(it);
                    //treeNode.setChildren(new ArrayList<>());
                    //treeNode.add(it);
                }
            }
            treeNode.setChildren(children);
        }
        return trees;
    }

    /**
     * 使用递归方法建树
     *
     * @param treeNodes
     * @return
     */
    public <T extends TreeNode> List<T> buildByRecursive(List<T> treeNodes, Object root) {
        List<T> trees = new ArrayList<T>();
        for (T treeNode : treeNodes) {
            if (root.equals(treeNode.getParentId())) {
                trees.add(findChildren(treeNode, treeNodes));
            }
        }
        return trees;
    }

    /**
     * 递归查找子节点
     *
     * @param treeNodes
     * @return
     */
    public <T extends TreeNode> T findChildren(T treeNode, List<T> treeNodes) {
        for (T it : treeNodes) {
            if (treeNode.getId() == it.getParentId()) {
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(new ArrayList<>());
                }
                treeNode.add(findChildren(it, treeNodes));
            }
        }
        return treeNode;
    }

    /**
     * 通过sysMenu创建树形节点
     *
     * @param types
     * @param root
     * @return
     */
    public List<ProductTypeTree> bulidTree(List<ProductTypeTree> types, String root) {
        List<ProductTypeTree> trees = new ArrayList<>();
        ProductTypeTree node;
        for (ProductTypeTree type : types) {
            node = new ProductTypeTree();
            node.setId(type.getId());
            node.setParentId(type.getPid());
            node.setName(type.getName());
            trees.add(node);
        }
        return TreeUtil.bulid(trees, root);
    }
}
